package com.yang.contorller;



import com.yang.exception.BusinessException;
import com.yang.utils.Constants;
import com.yang.utils.FileDfsUtil;
import com.yang.utils.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by 杨天可 on 2022/3/29 10:57
 *
 * 该接口只提供图片文件的上传
 */

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Resource
    private FileDfsUtil fileDfsUtil ;


    @PostMapping("/myUpload")
    public Map<String, Object> myUpload(@RequestParam("file") MultipartFile file) {
        //不能上传空文件
        if (file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String subfix = originalFilename.substring(originalFilename.indexOf(".") + 1);
        //此处限制了上传文件为图片文件，若需上传其他文件，注释此处的if判断即可
        if (!(subfix.equals("jpeg") || subfix.equals("png") || subfix.equals("jpg") || subfix.equals("gif"))) {
            throw new BusinessException("只能上传png，jpg，jpeg，gif格式的图片");
        }

        JsonResult jsonResult = new JsonResult();
        try {
            String path = fileDfsUtil.upload(file) ;
            if (!StringUtils.isEmpty(path)){
                jsonResult.setCode(Constants.SUCCESS);
                jsonResult.setMsg("上传成功");
                jsonResult.setData(path);
            } else {
                jsonResult.setCode(Constants.FAIL);
                jsonResult.setMsg("上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonResult.getValues();
    }

    @GetMapping("/deleteFile")
    public Map<String, Object> deleteFile(@RequestParam("filePath") String filePath) {
        JsonResult jsonResult = new JsonResult();
        fileDfsUtil.deleteFile(filePath);
        jsonResult.setMsg("删除成功");
        jsonResult.setCode(Constants.SUCCESS);
        return jsonResult.getValues();
    }

    @GetMapping("/download")
    public void download(@RequestParam("filePath") String filePath, HttpServletResponse response) throws IOException {
        if(StringUtils.isNotBlank(filePath)){
            fileDfsUtil.download(filePath,response);
        }
    }
}